<?php
namespace app\api\controller\direct;
use app\common\controller\Api;
use app\common\model\direct\OrderModel;
use app\common\model\meet\Config;
use EasyWeChat\Factory;
use think\Request;


class Order extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];
    private $model ;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model  = new OrderModel();
    }

    public function createOne($storeId,$amount,$remark=""){
        $userId=$createUid=$this->auth->id;
        $orderId=$this->model->createOne($storeId,$amount,$userId,$createUid,$remark);
        $this->success('',$orderId);
    }
    public function createOneAndPay($storeId,$amount,$remark=""){
        $userId=$createUid=$this->auth->id;
        $orderId=$this->model->createOne($storeId,$amount,$userId,$createUid,$remark);
        $this->payOne($orderId);
    }
    public function payOne($orderId)
    {
        $order=$this->model->find($orderId);
        if (!$order)$this->error('订单不存在');
        $notify_url = $this->request->root(true) . '/api/direct.order/notify';
        $result = $this->model->payOrder($orderId, $notify_url);
        if (!$result) {
            $this->error($this->model->getErr());
        }else{
            $this->success('', $result);
        }
    }
    public function notify(){
        Factory::payment(Config::getPayConfig())->handlePaidNotify(function ($message, $fail) {
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //商户订单号
                    $out_trade_no = $message['out_trade_no'];
                    //微信支付订单号
                    $transaction_id = $message['transaction_id'];
                    $order_info = $this->model->where('order_no', '=', $out_trade_no)->find();
                    if (empty($order_info)) {
                        //订单不存，订单不做处理，通知微信处理完成。
                        return true;
                    }

                    if ($order_info['status'] == $this->model::STATUS_PAYED) {
                        //订单支付状态，订单不做处理，通知微信处理完成。
                        return true;
                    }
                    $order_info->transaction_id=$transaction_id;
                    $order_info->status=$this->model::STATUS_PAYED;
                    $order_info->save();

                } elseif ($message['result_code'] === 'FAIL') {
                    // 用户支付失败
                    return true; // 返回处理完成
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });
    }
}